<!--字典数据-->
<template>
    <el-form :model="dictform" ref="dictref" :inline="true" style="text-align: left;">
        <el-form-item label="标签:" prop="label">
            <el-input placeholder="请输入" v-model="dictform.label"></el-input>
        </el-form-item>
        <el-form-item label="状态:" prop="status">
            <el-select placeholder="请选择" style="width:200px" v-model="dictform.status">
                <el-option value="0" label="启用">启用</el-option>
                <el-option value="1" label="禁用">禁用</el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="操作人:" prop="createname">
            <el-input placeholder="请输入" v-model="dictform.createname"></el-input>
        </el-form-item>
        <el-form-item label="操作时间:" prop="timeRange">
            <el-date-picker v-model="dictform.timeRange"  :value-format="dateFormat" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date"/>
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button type="success" @click="drawer = true">添加</el-button>
        <el-button type="danger" @click="DeleteAll">删除</el-button>
        <el-button @click="Export">导出</el-button>
        <el-button @click="goBack">返回</el-button>
    </div>
    <!--表格-->
    <el-table :data="dictdata" style="margin-top: 10px;" @selection-change="SelectChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column type="index" label="序号" width="70"></el-table-column>
        <el-table-column prop="dict_label" label="标签"></el-table-column>
        <el-table-column prop="dict_value" label="键值"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column prop="dict_type" label="字典类型"></el-table-column>
        <el-table-column prop="create_name" label="操作人"></el-table-column>
        <el-table-column prop="create_time" label="操作时间"></el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="success" text="编辑" @click="ShowUpdate(scope.row.dict_code)">编辑</el-button>
                <el-button type="danger" text="删除" @click="ShowDelete(scope.row.dict_code)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

     <!-- 页码 -->
     <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>

     <!--添加抽屉-->
     <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: left;">添加</h4>
        </template>
        <template #default>
            <el-form :model="addform" ref="addformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-form-item label="标签" prop="label">
                    <el-input placeholder="请输入" v-model="addform.label"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input placeholder="请输入" v-model="addform.sort"></el-input>
                </el-form-item>
                <el-form-item label="键值" prop="value">
                    <el-input placeholder="请输入" v-model="addform.value"></el-input>
                </el-form-item>
                <el-form-item label="字典类型" prop="dictid">
                    <el-select placeholder="请选择" v-model="addform.dictid" style="width:200px" @change="handleDictTypeChange">
                        <el-option v-for="item in dictTypes" :key="item.dict_id" :label="item.dict_typename" :value="item.dict_id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否默认" prop="default">
                    <el-radio-group v-model="addform.default">
                        <el-radio value="1">是</el-radio>
                        <el-radio value="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="addform.status">
                        <el-radio value="0">启用</el-radio>
                        <el-radio value="1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" placeholder="请输入" v-model="addform.remark"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="Add">确定</el-button>
            </div>
        </template>
    </el-drawer>


     <!--修改抽屉-->
     <el-drawer v-model="drawer2">
        <template #header>
            <h4 style="text-align: left;">修改</h4>
        </template>
        <template #default>
            <el-form :model="updateform" ref="updateformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-form-item label="标签" prop="label">
                    <el-input placeholder="请输入" v-model="updateform.label"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input placeholder="请输入" v-model="updateform.sort"></el-input>
                </el-form-item>
                <el-form-item label="键值" prop="value">
                    <el-input placeholder="请输入" v-model="updateform.value"></el-input>
                </el-form-item>
                <el-form-item label="字典类型" prop="dictid">
                    <el-select placeholder="请选择" v-model="updateform.dictid" style="width:200px" @change="handleDictTypeChange">
                        <el-option v-for="item in dictTypes" :key="item.dict_id" :label="item.dict_typename" :value="item.dict_id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否默认" prop="default">
                    <el-radio-group v-model="updateform.default">
                        <el-radio value="1">是</el-radio>
                        <el-radio value="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="updateform.status">
                        <el-radio value="0">启用</el-radio>
                        <el-radio value="1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" placeholder="请输入" v-model="updateform.remark"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer2 = false">取消</el-button>
                <el-button type="primary" @click="Update">确定</el-button>
            </div>
        </template>
    </el-drawer>

    <!--删除模态框-->
    <el-dialog v-model="DeleteialogVisible" width="400" style="text-align: left;"  align-center>
        <span>确定删除吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Delete()">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import {ref,reactive,onMounted} from 'vue'
import http from '../auth/index';
import { ElMessage } from 'element-plus'; //提示信息
import * as XLSX from 'xlsx';
import { useRoute,useRouter  } from 'vue-router';//路由
export default {
setup()
    {
        const route = useRoute();//路由（获取参数）
        const router = useRouter();//路由（实现跳转）
        //字典类型传过来的ID
        const dicttypeid = route.params.dicttypeid;
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));

        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //规则验证
        const rules = reactive({
            label: [
                { required: true, message: '请输入标签', trigger: 'blur' },
            ],
            sort: [
                { required: true, message: '请输入', trigger: 'blur' },
                { pattern: /^\d+$/, message: '只能是数字', trigger: 'blur' }
            ],
            value: [
                { required: true, message: '请输入键值', trigger: 'blur' },
            ],
            dictid:[
                { required: true, message: '请选择', trigger: 'blur' },
            ]
        });

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }

        //导出
        function Export(){
            if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要导出的数据.',
                    type: 'warning',
                })
                return;
            }
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 准备数据
            const excelData = selectdata.value.map((row) => ({
                "序号": row.dict_code,
                "标签": row.dict_label,
                "排序": row.dict_sort,
                "状态": row.status,
                "字典类型": row.dict_type,
                "操作人": row.create_name,
                "操作时间": row.create_time
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet (excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "字典数据");
            // 导出并下载
            XLSX.writeFile(wb, `字典数据${new Date().toLocaleDateString()}.xlsx`);
        }

        //当前dictid
        const dictid=ref(0);

        //点击返回
        function goBack(){
            router.back();
        }

        //查询所有字典类型并绑定到下拉框
        const dictTypes=ref([]);
        function Alltype(){
            http.get("/DictType/GetType")
            .then(res=>{
                dictTypes.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        // 处理字典类型选择变化,将类型名称赋值
        function handleDictTypeChange(value) {
            const selectedItem = dictTypes.value.find(item => item.dict_id === value);
            if (selectedItem) {
                addform.dicttype = selectedItem.dict_typename;
                updateform.dicttype = selectedItem.dict_typename;
            }
        }

        //#region 查询

        //表单
        const dictref = ref("");
        const dictform = reactive({
            label: "",
            status: "",
            createname: "",
            timeRange: [null, null],
        })
        //表格数据
        const dictdata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);
        //日期格式
        const dateFormat = 'YYYY-MM-DD HH:mm:ss';

        //重置
        function Reset() {
            dictref.value?.resetFields();
            All();
        }

        //查询
        function Search() {
            All();
        }

        //查询数据
        function All() {
            http.get("/DictData/GetDictDataByType", {
                params: {
                    label: dictform.label,
                    status: dictform.status,
                    createname: dictform.createname,
                    starttime: dictform.timeRange[0],
                    endtime: dictform.timeRange[1],
                    typeid:dicttypeid,
                    CurrentPage: currentPage.value
                }
            }).then(res => {
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换
                const Data = res.data.list.map(item => ({
                    ...item, // 复制原始对象的所有属性
                    create_time: formatDateTime(new Date(item.create_time)),
                    status: item.status === 0 ? '启用' : '禁用'
                }));
                dictdata.value = Data;
            }).catch(err => {
                console.log(err)
            })
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }


        //#endregion


        //#region 添加

        //添加抽屉
        const drawer = ref(false);

        const addformref = ref("");
        //添加表单
        const addform = reactive({
            sort:"1",
            label: "",
            value:"",
            default:"0",
            status: "0",
            remark: "",
            dictid:"",
            dicttype:"",
            create_name: user.name,
            create_time: new Date(),
        })

        //添加
        function Add() {
            addformref.value.validate((valid) => {
                if (valid) {
                    //添加数据
                    const adddata = {
                        dict_sort: addform.sort,
                        dict_label: addform.label,
                        dict_value:addform.value,
                        is_default:addform.default,
                        dict_id:addform.dictid,
                        dict_type:addform.dicttype,
                        status:addform.status,
                        remark: addform.remark,
                        create_name: addform.create_name,
                        create_time: formatDateTime(addform.create_time),
                    }
                    http.post("/DictData/AddDictData",adddata)
                    .then(res => {
                        if (res.data> 0) {
                            ElMessage({
                                message: '添加成功.',
                                type: 'success',
                            })
                            All();
                            //清除表单
                            addformref.value?.resetFields();
                        }
                    }).catch(err => {
                        console.log(err);
                    })
                }
            })
        }


        //#endregion


        //#region 修改

        //修改抽屉
        const drawer2=ref(false);
        //修改表单
        const updateformref=ref("");
        const updateform = reactive({
            code:"",
            sort:"",
            label: "",
            value:"",
            default:"",
            status: "",
            remark: "",
            dictid:"",
            dicttype:"",
            update_name: user.name,
            update_time: new Date(),
        })
        //显示修改
        function ShowUpdate(id){
            drawer2.value=true;
            dictid.value=id;
            //根据当前id查询信息
            http.get("/DictData/GetDictDataById?id="+id)
            .then(res=>{
                updateform.code=res.data.dict_code;
                updateform.sort=res.data.dict_sort;
                updateform.label=res.data.dict_label;
                updateform.value=res.data.dict_value;
                updateform.default=res.data.is_default.toString();
                updateform.status=res.data.status.toString();
                updateform.remark=res.data.remark;
                updateform.dictid=res.data.dict_id;
                updateform.dicttype=res.data.dict_type;
            }).catch(err=>{
                console.log(err);
            })
        }
        //修改
        function Update(){
            //修改数据
            const updatedata ={
                dict_code: updateform.code,
                dict_sort: updateform.sort,
                dict_label: updateform.label,
                dict_value: updateform.value,
                is_default: updateform.default,
                dict_id:updateform.dictid,
                dict_type:updateform.dicttype,
                status:updateform.status,
                remark: updateform.remark,
                update_name: updateform.update_name,
                update_time: formatDateTime(updateform.update_time),
            }
            http.put("/DictData/UpdateDictData",updatedata)
            .then(res=>{
                if(res.data>0){
                    ElMessage({
                        message: '修改成功.',
                        type: 'success',
                    })
                    All();
                }
            }).catch(err=>{
                console.log(err);
            })
        }

        //#endregion


        //#region 删除

         //删除模态框
         const DeleteialogVisible=ref(false);
            //删除模态框
            function ShowDelete(id){
                dictid.value=id;
                DeleteialogVisible.value=true;
            }
            function Delete(){
                http.put("/DictData/DeleteDictData?id="+dictid.value)
                .then(res=>{
                    if(res.data>0){
                        ElMessage({
                            message: '删除成功.',
                            type: 'success',
                        })
                        All();
                        DeleteialogVisible.value=false;
                    }else{
                        ElMessage.error('删除失败.')
                    }
                }).catch(err=>{
                    console.log(err);
                })
            }
            //批量删除
            function DeleteAll(){
                if(selectdata.value.length==0){
                    ElMessage({
                        message: '请选择要删除的数据.',
                        type: 'warning',
                    })
                    return;
                }
                //循环删除
                selectdata.value.forEach(item => {
                    http.put("/DictData/DeleteDictData?id="+item.dict_code)
                    .then(res=>{
                        if(res.data>0){
                            ElMessage({
                                message: '删除成功.',
                                type: 'success',
                            })
                            All();
                            DeleteialogVisible.value=false;
                        }else{
                            ElMessage.error('删除失败.')
                        }
                    }).catch(err=>{
                        console.log(err);
                    })
                });
            }

        //#endregion

        //挂载
        onMounted(() => {
            All();
            Alltype();
        });

        return{
            dicttypeid,
            goBack,
            user,
            formatDateTime,
            selectdata,
            SelectChange,
            Export,
            dictid,
            dictref,
            dictform,
            dictdata,
            rows,
            currentPage,
            dateFormat,
            Reset,
            Search,
            All,
            handlePageChange,
            drawer,
            addform,
            addformref,
            Add,
            rules,
            dictTypes,
            handleDictTypeChange,
            drawer2,
            updateform,
            updateformref,
            Update,
            ShowUpdate,
            DeleteialogVisible,
            ShowDelete,
            Delete,
            DeleteAll
        }
    }
}
</script>

<style scoped>

</style>